<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Web Worker 示例</title>
</head>
<body>
<h1>Web Worker 示例</h1>

<button onclick="startWorker()">启动 Worker</button>
<button onclick="stopWorker()">停止 Worker</button>

<p id="result"></p>

<script>
  let worker;

  function startWorker() {
    if (typeof(Worker) !== "undefined") {
      if (typeof(worker) == "undefined") {
        worker = new Worker("worker.js");

        // 监听从 Worker 发送的消息
        worker.onmessage = function(event) {
          document.getElementById("result").innerHTML = event.data;
        };
      }
    } else {
      document.getElementById("result").innerHTML = "抱歉，你的浏览器不支持 Web Workers。";
    }
  }

  function stopWorker() {
    worker.terminate();
    worker = undefined;
  }
</script>
</body>
</html>
